package zy.blue7.gui.chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 * @Author: blue7
 * @Date: 2022/2/24 20:37
 * @Version 1.0
 * @Description
 */
public class ChatClient {
    private JButton clientButton;
    private JPanel panel1;
    private JTextField message;
    private JTextArea getMessage;
    private Channel channel = null;

    public static void main(String[] args) {
        JFrame frame = new JFrame("ChatClient");
        frame.setContentPane(new ChatClient().panel1);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 400);
        frame.setLocation(700, 200);
        frame.setVisible(true);
    }

    public ChatClient() {
        /**
         * 程序启动的时候启动client， 连接 服务器
         */
        try {
            this.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        /**
         * 当点击按钮的时候，发送消息给服务器
         */
        clientButton.addActionListener(e -> {
            this.send(message.getText());
        });
        /**
         * 回车也发生消息
         */
        message.addActionListener(e -> {
            this.send(message.getText());
        });
    }


    public void start() throws InterruptedException {

        //1.启动类
        this.channel = new Bootstrap()
                // 2.添加 EventLoop
                .group(new NioEventLoopGroup())
                //3. 选择客户端 channel实现
                .channel(NioSocketChannel.class)
                //4.添加处理器
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override // todo 在建立链接的时候调用
                    protected void initChannel(NioSocketChannel ch) throws Exception {

                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                String text = getMessage.getText();
                                if (null != text && !text.trim().equalsIgnoreCase(""))
                                    getMessage.setText(text + "\r\n" + ((ByteBuf)msg).toString(CharsetUtil.UTF_8));
                                else getMessage.setText(((ByteBuf)msg).toString(CharsetUtil.UTF_8));
                            }
                        });
//                        ch.pipeline().addLast(new StringEncoder());
//                        ch.pipeline().addLast(new StringDecoder());
                    }
                })
                //5.连接到服务器
                .connect(new InetSocketAddress("localhost", 8080))
                .sync() //todo 阻塞方法，知道链接建立
                .channel();
        // 6.向服务器发送数据
//                .writeAndFlush("hello world");
    }

    public void send(String str) {
        channel.writeAndFlush(Unpooled.copiedBuffer(str, CharsetUtil.UTF_8));
    }
}
